#include "bsp_key.h"

struct key_dev key0 = {0};

/* 5ms获取一次按键状态 */
void key_val_get(void)
{
	key0.val[0] = key0.val[1];
	key0.val[1] = key0.val[2];
	key0.val[2] = key0.val[3];
	key0.val[3] = !gpio_input_bit_get(TOUCH_CTRL_PORT, TOUCH_CTRL_PIN);
	
	key0.last_state = key0.cur_state;

	if (key0.val[0] == PRESSED
	&& key0.val[1] == PRESSED
	&& key0.val[2] == PRESSED
	&& key0.val[3] == PRESSED)
	{
		key0.cur_state = PRESSED;
		key0.release_time = 0;
	}
	else if (key0.val[0] == RELEASE
	&& key0.val[1] == RELEASE
	&& key0.val[2] == RELEASE
	&& key0.val[3] == RELEASE)
	{
		key0.cur_state = RELEASE;
		key0.pressed_time = 0;
	}
}

void key_event_get(void)
{
	if (key0.cur_state == PRESSED)
	{
		key0.pressed_time++;

		if (key0.wait_double_flag == 1)
		{
			key0.wait_double_flag = 2;
		}

		if (key0.pressed_time >= TIMER_5MS_3S)
		{
			key0.press_hold_flag = 1;
		}
	}
	else
	{
		if ((key0.last_state == PRESSED) && (key0.wait_double_flag == 0))
		{
			key0.wait_double_flag = 1;
		}

		if ((key0.wait_double_flag == 1) && (key0.release_time++ >= DOUBLE_CLICK_DELAY))
		{
			my_memset((char*)&key0, 0, sizeof(key0));
			key0.key_event = CLICK;  //单击事件
		}

		if (key0.wait_double_flag == 2)
		{
			my_memset((char*)&key0, 0, sizeof(key0));
			key0.key_event = DOUBLE_CLICK;  //双击事件
		}

		if (key0.press_hold_flag == 1)
		{
			my_memset((char*)&key0, 0, sizeof(key0));
			key0.key_event = LONG_CLICK;  //长按事件
		}
	}
}

/* 5ms */
void key_event_handle(void)
{
    if (key0.key_event != NONE)
    {
        if (key0.key_event == CLICK)
        {
            BEEP_CTRL_EN;   // 触摸 蜂鸣器拉高
            gLcdSleepFlag = 0;
            if (gpio_output_bit_get(LCDK_CTRL_PORT, LCDK_CTRL_PIN) == SET)
            {
                LCDK_CTRL_DIS;
            }
            else
            {
                LCDK_CTRL_EN;
            }

            g_lcd_manager.power_off_cnt = 0;
            g_lcd_manager.lcd_off_cnt = 0;
        }
        
        my_memset((char*)&key0, 0, sizeof(key0));
    }
    else
    {
        BEEP_CTRL_DIS;
    }

}

